import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message,
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import './index.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { useState, useEffect, useRef } from 'react'
import { useSearchParams } from 'react-router-dom'
import { http } from '@/utils'

const { Option } = Select

const Publish = () => {
  const [channels, setChanels] = useState([])
  useEffect(() => {
    async function getChannels() {
      const res = await http.get('/channels')
      setChanels(res.data.data.channels)
    }
    getChannels()
  }, [])
  const [fileList, setFileList] = useState([])
  const onUploadChange = (info) => {
    const fileList = info.fileList.map((file) => {
      if (file.response) {
        return {
          url: file.response.data.url,
        }
      }
      return file
    })
    fileListRef.current = fileList
    setFileList(fileList)
  }
  const [imgCount, setImgCount] = useState(1)
  const fileListRef = useRef([])
  const typeChange = (e) => {
    setImgCount(e.target.value)
    if (e.target.value === 1) {
      // 单图，只展示第一张
      const firstImg = fileListRef.current[0]
      setFileList(!firstImg ? [] : [firstImg])
    } else if (e.target.value === 3) {
      // 三图，展示所有图片
      setFileList(fileListRef.current)
    }
  }
  const [messageApi, contextHolder] = message.useMessage()
  const onFinish = async (values) => {
    // 数据的二次处理 重点是处理cover字段
    const { channel_id, content, title, type } = values
    const params = {
      channel_id,
      content,
      title,
      type,
      cover: {
        type: type,
        images: fileList.map((item) => item.url),
      },
    }
    let res
    if (articleId) {
      // 编辑
      res = await http.put(`/mp/articles/${articleId}?draft=false`, params)
    } else {
      // 新增
      res = await http.post('/mp/articles?draft=false', params)
    }
    if (res.status === 200) {
      messageApi.info(articleId ? '修改成功' : '发布成功')
    } else {
      messageApi.open({
        type: 'error',
        content: '出错了，请联系猫头鹰',
      })
    }
  }
  const [params] = useSearchParams()
  const articleId = params.get('id')
  const formRef = useRef(null)
  useEffect(() => {
    async function getArticle() {
      const res = await http.get(`/mp/articles/${articleId}`)
      const { cover, ...formValue } = res.data.data
      // 动态设置表单数据
      formRef.current.setFieldsValue({ ...formValue, type: cover.type })
      // 格式化封面图片数据
      const imageList = cover.images.map((url) => ({ url }))
      setFileList(imageList)
      setImgCount(cover.type)
      fileListRef.current = imageList
    }
    if (articleId) {
      // 拉取数据回显
      getArticle()
    }
  }, [articleId])
  return (
    <div className="publish">
      {contextHolder}
      <Card
        title={
          <Breadcrumb
            items={[
              { title: '首页', href: '/' },
              { title: articleId ? '修改文章' : '发布文章' },
            ]}
          />
        }>
        <Form
          ref={formRef}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1, content: '' }}
          onFinish={onFinish}>
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}>
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}>
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {channels.map((item) => {
                return (
                  <Option value={item.id} key={item.id}>
                    {item.name}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={typeChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {imgCount ? (
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                action="http://geek.itheima.net/v1_0/upload"
                fileList={fileList}
                onChange={onUploadChange}
                maxCount={imgCount}>
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            ) : null}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}>
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {articleId ? '修改文章' : '发布文章'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish
